#import <Foundation/Foundation.h>
#import <objc/runtime.h>

#import "framework/FWCommon.h"

#import "PIContext.h"


@implementation PIContext

@synthesize key, title, selected, count, locationAware;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

+ (PIContext*)contextForKey:(NSInteger)newKey title:(NSString*)newTitle
{
    PIContext* context = [[[PIContext alloc] init] autorelease];
    
    context->key = newKey;
    context->title = [newTitle copy];
    
    return context;
}

+ (PIContext*)contextForKey:(NSInteger)newKey title:(NSString*)newTitle selected:(BOOL)newSelected
{
    PIContext* context = [[[PIContext alloc] init] autorelease];
    
    context->key = newKey;
    context->title = [newTitle copy];
    context->selected = newSelected;
    
    return context;
}

- (void)dealloc
{
    [title release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Debugging functions

- (NSString*)description
{
    return [NSString stringWithFormat:
            @"<%@: %p;"
            " key = %i;"
            " title = %@;"
            " selected = %i;"
            " locationAware = %i;"
            " count = %i>",
            [self class],
            self,
            self.key,
            self.title,
            self.selected,
            self.locationAware,
            self.count];
}

@end


// ******************************************************************************************
#pragma mark -
#pragma mark Object access from arrays

@implementation NSArray (PIContext)

- (id)piContextForKey:(NSInteger)key
{
    NSInteger count = self.count;
    for (NSInteger i = 0; i < count; ++i) {
        PIContext* context = [self objectAtIndex:i];
        if (context.key == key)
            return context;
    }
    
    return nil;
}

@end